package com.ishowcode.controller.UserController;
import com.ishowcode.annotation.GlobalInterceptor;
import com.ishowcode.entity.*;
import com.ishowcode.service.MessageInfoService;
import com.ishowcode.service.ToEmailService;
import com.ishowcode.service.UserInfoService;
import com.ishowcode.utils.BizException;
import com.ishowcode.utils.RedisUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
public class UserInfoController {
    String userkey ="user--";
    String yanzhengma = "yanzhengma--";
    @Autowired
    ToEmailService toEmailService;
    @Autowired
    UserInfoService userInfoService;
    @Resource
    MessageInfoService messageInfoService;
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Resource
    RedisUtil redisUtil;
    @PostMapping("/register")
    @GlobalInterceptor(checkParam = true)
    public Result RegisterController(@RequestParam("email")  String email,@RequestParam("password")  String password,@RequestParam("code")  String code){
        if (code.equals(redisUtil.get(yanzhengma+email))&&redisUtil.get(yanzhengma+email)!=null){
            User user = new User();
            user.setEmail(email);
            user.setNickName(email);
            user.setPassWord(password);
            Calendar ca = Calendar.getInstance();
            Date dNow = ca.getTime();
            String id = String.valueOf(System.currentTimeMillis());
            user.setUserId(String.valueOf(id.substring(id.length()-6)+email.substring(0,6)));
            user.setJoinTime(dNow);
            user.setLastLoginTime(dNow);
            user.setStatus(1);
            user.setTotalSpace((long) 104857600);
            user.setUseSpace((long) 0);
            if (userInfoService.addUser(user).intValue()>=1){
                Message message = new Message();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                message.setMessageId(uuid);
                message.setMessageContent("欢迎您"+user.getNickName()+"使用简易云盘");
                message.setUserId(user.getUserId());
                message.setCreateTime(dNow);
                messageInfoService.addMessage(message);
                return Result.success("成功");
            }else {
                return Result.failure("失败");
            }
        }else {
            return Result.failure("验证码错误");
        }


    }
    @RequestMapping("/sendemailRe")
    @GlobalInterceptor(checkParam = true)
    public synchronized Result  SendEmail(@RequestParam("email")  String email){
        User user = userInfoService.queryUserByEmail(email);
        if (user!=null){
            return Result.failure("邮箱已经被注册");
        }
        if(redisUtil.get(yanzhengma+email)==null){
            Email email1 = new Email(email,"验证码","");
            String reCode= toEmailService.commonEmail(email1);
            if (reCode!=""){
                redisUtil.set(yanzhengma+email,reCode);
                redisUtil.expire(yanzhengma+email,180);
                return Result.success("成功");
            }else {
                return Result.failure("失败");
            }
        }else {
            return Result.failure("验证码请求太频繁了,3分钟内有效哦!");
        }



    }
//    @PostMapping("/login")
//    @GlobalInterceptor(checkParam = true)
//    public Result LoginController(@RequestBody User user1,HttpServletRequest request, @RequestHeader Map<String,String> headers){
//        User user = userInfoService.queryUserByEmail(user1.getEmail());
//        if (user!=null){
//            if (user.getPassWord().equals(user1.getPassWord())){
//                User userInfo = new User();
//                userInfo.setNickName(user.getNickName());
//                userInfo.setEmail(user.getEmail());
//                Calendar ca = Calendar.getInstance();
//                Date dNow = ca.getTime();
//                user.setLastLoginTime(dNow);
//                userInfoService.updateUser(user);
//                redisTemplate.opsForValue().set(userkey+user.getEmail(),user);
//                redisUtil.expire(userkey+user.getEmail(),3600);
//                //
//                Message message = new Message();
//                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//                message.setMessageId(uuid);
//                message.setUserId(user.getUserId());
//                message.setCreateTime(dNow);
//                String ip ;
//                if  (request.getHeader("x-forwarded-for") ==null)  {
//                    ip = request.getRemoteAddr();
//                } else  {
//                    ip = request.getHeader("x-forwarded-for");
//                }
//                if  ("127.0.0.1".equals(ip))  {
//                    try {
//                        // 获取本机真正的ip地址
//                        ip = InetAddress.getLocalHost().getHostAddress();
//                    }catch (Exception e){
//                        e.printStackTrace();
//                    }
//                }
//                //解析agent字符串
//                UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
//                //获取浏览器对象
//                Browser browser = userAgent.getBrowser();
//                //获取操作系统对象
//                OperatingSystem operatingSystem = userAgent.getOperatingSystem();
//                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//                message.setMessageContent(user.getNickName()+",您于："+ft.format(dNow)+",登录ip为:"+ip+",使用"+browser+"浏览器,"+operatingSystem+"操作系统"+"登录简易云盘,如不是本人操作，请注意账号安全");
//                messageInfoService.addMessage(message);
//                //
//                return Result.success(userInfo);
//            }else {
//                return Result.failure("邮箱或密码错误");
//            }
//        }else {
//            return Result.failure("登录错误");
//        }
//
//    }
    @PostMapping("/login")
    @GlobalInterceptor(checkParam = true)
    public Result LoginController(@RequestParam("email")  String email, @RequestParam("password")  String password,HttpServletRequest request, @RequestHeader Map<String,String> headers){
        User user = userInfoService.queryUserByEmail(email);
        if (user!=null){
            if (user.getPassWord().equals(password)){
                User userInfo = new User();
                userInfo.setNickName(user.getNickName());
                userInfo.setEmail(user.getEmail());
                Calendar ca = Calendar.getInstance();
                Date dNow = ca.getTime();
                user.setLastLoginTime(dNow);
                userInfoService.updateUser(user);
                redisTemplate.opsForValue().set(userkey+user.getEmail(),user);
                redisUtil.expire(userkey+user.getEmail(),3600);
                //
                Message message = new Message();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                message.setMessageId(uuid);
                message.setUserId(user.getUserId());
                message.setCreateTime(dNow);
                String ip ;
                if  (request.getHeader("x-forwarded-for") ==null)  {
                    ip = request.getRemoteAddr();
                } else  {
                    ip = request.getHeader("x-forwarded-for");
                }
                if  ("127.0.0.1".equals(ip))  {
                    try {
                        // 获取本机真正的ip地址
                        ip = InetAddress.getLocalHost().getHostAddress();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                //解析agent字符串
                UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
                //获取浏览器对象
                Browser browser = userAgent.getBrowser();
                //获取操作系统对象
                OperatingSystem operatingSystem = userAgent.getOperatingSystem();
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                message.setMessageContent(user.getNickName()+",您于："+ft.format(dNow)+",登录ip为:"+ip+",使用"+browser+"浏览器,"+operatingSystem+"操作系统"+"登录简易云盘,如不是本人操作，请注意账号安全");
                messageInfoService.addMessage(message);
                //
                return Result.success(userInfo);
            }else {
                return Result.failure("邮箱或密码错误");
            }
        }else {
            return Result.failure("登录错误");
        }

    }
    @GetMapping("/getInfo")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result getUserInfo(@RequestParam("email")  String email, @RequestHeader Map<String,String> headers,HttpServletRequest request){
        User userLogin = (User) redisTemplate.opsForValue().get(userkey+email);
        if (userLogin.getEmail().equals(email)){
            User user = userInfoService.queryUserByEmail(email);
            User userInfo = new User();
            userInfo.setNickName(user.getNickName());
            userInfo.setStatus(user.getStatus());
            userInfo.setEmail(user.getEmail());
            userInfo.setUseSpace(user.getUseSpace());
            userInfo.setTotalSpace(user.getTotalSpace());
            userInfo.setLastLoginTime(user.getLastLoginTime());
            Map<String, Object> usermap = new HashMap<>();
            usermap.put("userInfo",userInfo);
            usermap.put("isvip",false);
            String ip ;
            if  (request.getHeader("x-forwarded-for") ==null)  {
                ip = request.getRemoteAddr();
            } else  {
                ip = request.getHeader("x-forwarded-for");
            }
            if  ("127.0.0.1".equals(ip))  {
                try {
                    // 获取本机真正的ip地址
                    ip = InetAddress.getLocalHost().getHostAddress();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            usermap.put("loginarea",ip);
            //解析agent字符串
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            //获取浏览器对象
            Browser browser = userAgent.getBrowser();
            //获取操作系统对象
            OperatingSystem operatingSystem = userAgent.getOperatingSystem();
            String userbrower = browser.getName()+" | "+operatingSystem.getName()+" | "+operatingSystem.getDeviceType();
            usermap.put("userbrower",userbrower);
            if (user!=null){
                return Result.success(usermap);
            }else {
                return  Result.failure("查询失败");
            }
        }else {
            return  Result.failure("这不是你的账号哦，查询失败");
        }

    }
    @GetMapping("/updateNickName")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result updateNickName(@RequestParam("email")  String email,@RequestParam("nickname") String nickname){
        User user = userInfoService.queryUserByEmail(email);
        String oldname = user.getNickName();
        User usercheck = userInfoService.queryUserByNickName(nickname);
        if (null!=usercheck){
            return Result.failure("昵称已被占用");
        }else {
            user.setNickName(nickname);
            Integer rows = userInfoService.updateUser(user);
            if (rows.intValue()>=1){
                redisTemplate.opsForValue().set(userkey+user.getEmail(),user);
                redisUtil.expire(userkey+user.getEmail(),3600);
                Message message = new Message();
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                message.setMessageId(uuid);
                message.setUserId(user.getUserId());
                Calendar ca = Calendar.getInstance();
                Date dNow = ca.getTime();
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                message.setCreateTime(dNow);
                message.setMessageContent("您于:"+ft.format(dNow)+"将昵称:"+oldname+" 改为:"+user.getNickName());
                messageInfoService.addMessage(message);
                return Result.success("成功");
            }else {
                return Result.failure("失败");
            }
        }

    }
    @GetMapping("/updateEmail")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result updateEmail(@RequestParam("oldemail")  String oldemail,@RequestParam("newemail") String newemail,@RequestParam("code") String code,@RequestParam("password") String password){
        if (((User)redisUtil.get(userkey+oldemail)).getPassWord().equals(password)){
            if(redisUtil.get(yanzhengma+newemail)!=null&&code.equals(redisUtil.get(yanzhengma+newemail))){
                User user = userInfoService.queryUserByEmail(oldemail);
                user.setEmail(newemail);
                Integer rows = userInfoService.updateUser(user);
                redisTemplate.delete(userkey+oldemail);
                if (rows.intValue()>=1){
                    redisTemplate.opsForValue().set(userkey+user.getEmail(),user);
                    redisUtil.expire(userkey+user.getEmail(),3600);
                    Message message = new Message();
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    message.setMessageId(uuid);
                    message.setUserId(user.getUserId());
                    Calendar ca = Calendar.getInstance();
                    Date dNow = ca.getTime();
                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    message.setCreateTime(dNow);
                    message.setMessageContent("您于:"+ft.format(dNow)+"将邮箱:"+oldemail+" 改为:"+newemail);
                    messageInfoService.addMessage(message);
                    return Result.success("成功");
                }else {
                    return Result.failure("失败");
                }
            }else {
                BizException bizException = new BizException();
                bizException.setR(ResultCode.CODE_ERROR);
                throw bizException;
            }
        }else {
            BizException bizException = new BizException();
            bizException.setR(ResultCode.PassWord);
            throw bizException;
        }


    }
    @RequestMapping("/updatePass")
    @GlobalInterceptor(checkParam = true)
    public Result updatePass(@RequestParam("email")  String email,@RequestParam("password") String password,@RequestParam("code") String code){
        if (redisUtil.get(yanzhengma+email)!=null&&code.equals(redisUtil.get(yanzhengma+email))){
            User user = userInfoService.queryUserByEmail(email);
            if (user!=null){
                user.setPassWord(password);
                Integer rows = userInfoService.updateUser(user);
                if (rows.intValue()>=1){
                    redisTemplate.delete(userkey+email);
                    Message message = new Message();
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    message.setMessageId(uuid);
                    message.setUserId(user.getUserId());
                    Calendar ca = Calendar.getInstance();
                    Date dNow = ca.getTime();
                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    message.setCreateTime(dNow);
                    message.setMessageContent("您于:"+ft.format(dNow)+" 更改了密码");
                    messageInfoService.addMessage(message);
                    return Result.success("成功");
                }else {
                    return Result.failure("失败");
                }
            }else {
                return Result.failure("该邮箱未绑定");
            }
        }else {
            BizException bizException = new BizException();
            bizException.setR(ResultCode.CODE_ERROR);
            throw bizException;
        }


    }
    //TODO
    @RequestMapping("/sendemailUp")
    @GlobalInterceptor(checkParam = true)
    public synchronized Result SendEmailUp(@RequestParam("email")  String email){
            User user = userInfoService.queryUserByEmail(email);
            String reCode = "";
            if (user!=null){
                if(redisUtil.get(yanzhengma+email)==null){
                    Email email1 = new Email(email,"验证码","");
                    try {
                        reCode = toEmailService.commonEmail(email1);
                    }catch (BizException e){
                        e.setR(ResultCode.Email_Error);
                        throw  e;
                    }
                    if(reCode==""){
                        return Result.failure("失败");
                    }else {
                        redisUtil.set(yanzhengma+email,reCode);
                        redisUtil.expire(yanzhengma+email,60);
                        return Result.success("成功");
                    }
                }else {
                    return Result.failure("验证码请求太频繁了,3分钟内有效哦!");
                }


            }else return Result.failure("邮箱未注册");
    }
    //TODO
    @RequestMapping("/sendemailUpPass")
    @GlobalInterceptor(checkParam = true,checkLogin = true)
    public synchronized Result sendemailUpPass(@RequestParam("email")  String email){
        User user = userInfoService.queryUserByEmail(email);
        String reCode = "";
        if (user!=null){
            if(redisUtil.get(yanzhengma+email)==null){
                Email email1 = new Email(email,"验证码","");
                try {
                    reCode = toEmailService.commonEmail(email1);
                }catch (BizException e){
                    e.setR(ResultCode.Email_Error);
                    throw  e;
                }
                if(reCode==""){
                    return Result.failure("失败");
                }else {
                    redisUtil.set(yanzhengma+email,reCode);
                    redisUtil.expire(yanzhengma+email,60);
                    return Result.success("成功");
                }
            }else {
                return Result.failure("验证码请求太频繁了,3分钟内有效哦!");
            }


        }else return Result.failure("邮箱未注册");
    }
    @GetMapping("/loginout")
    @GlobalInterceptor(checkLogin = true,checkParam = true)
    public Result loginout(@RequestParam("email")  String email){
       redisTemplate.delete(userkey+email);
       return Result.success("成功");

    }
    @GetMapping("/totaluser")
    @GlobalInterceptor(checkLogin = true)
    public Result testsetSession(@RequestParam("email") String email){
        Set<String> user =  redisTemplate.keys(userkey.concat("*"));
        System.out.println(user.size());
        if (user==null){
            return Result.failure("失败");
        }else {
            return Result.success(user.size());
        }

    }


}
